﻿using CodeApi.Context;
using CodeApi.Models;
using CodeApi.tool;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Threading.Tasks;

namespace CodeApi.Controllers
{
    [Route("api/[controller]/action")]
    [ApiController]
    [Authorize]
    public class PictureBenController : ControllerBase
    {
        public PictureBenContext context;
        public IWebHostEnvironment environment;
        public String fileName;

        public PictureBenController(IWebHostEnvironment environment, PictureBenContext context)
        {
            this.context = context;
            this.environment = environment;
        }

        /// <summary>
        /// 上传图片 
        /// 需要检测上传文件是否是图片，以及文件大小的合法性
        /// </summary>
        /// <param name="pictureBed"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<String> PostPicture([FromForm] ImagePostModel pictureBed)
        {
            try
            {
                if (pictureBed.File.Length > 0)
                {
                    String path = this.environment.WebRootPath + "\\Pictures\\";
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    fileName = $"{TimesTampHelper.getTimesTamp().ToString()}{pictureBed.File.FileName.Substring(pictureBed.File.FileName.LastIndexOf('.'))}";
                    using (FileStream stream = System.IO.File.Create($"{path}{fileName}"))
                    {
                        pictureBed.File.CopyTo(stream);
                        stream.Flush();
                        var host = Request.Host;
                        context.PictureBed.Add(new PictureBedModel() { FileName = $"https://{host}/Pictures/{fileName}", PushDate = DateTime.Now, Remark = pictureBed.Remark });
                        await context.SaveChangesAsync();
                        return $"https://{host}/Pictures/{fileName}";
                    }
                }
                else
                {
                    return  String.Empty ;
                }
            }
            catch (Exception ex)
            {
                return  ex.Message ;
            }
        }
    }
}